package person.aoao.library.service.impl;

import person.aoao.library.entity.Cards;
import person.aoao.library.dao.CardsDao;
import person.aoao.library.entity.WillList;
import person.aoao.library.service.CardsService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import person.aoao.library.service.WillListService;

import javax.annotation.Resource;

/**
 * (Cards)表服务实现类
 *
 * @author makejava
 * @since 2023-05-06 01:37:54
 */
@Service("cardsService")
public class CardsServiceImpl implements CardsService {
    @Resource
    private CardsDao cardsDao;
    @Resource
    private WillListService willListService;
    /**
     * 通过ID查询单条数据
     *
     * @param cardid 主键
     * @return 实例对象
     */
    @Override
    public Cards queryById(Integer cardid) {
        return this.cardsDao.queryById(cardid);
    }

    /**
     * 分页查询
     *
     * @param cards       筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<Cards> queryByPage(Cards cards, PageRequest pageRequest) {
        long total = this.cardsDao.count(cards);
        return new PageImpl<>(this.cardsDao.queryAllByLimit(cards, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param cards 实例对象
     * @return 实例对象
     */
    @Override
    public Cards insert(Cards cards) {
        this.cardsDao.insert(cards);
        return cards;
    }

    /**
     * 修改数据
     *
     * @param cards 实例对象
     * @return 实例对象
     */
    @Override
    public Cards update(Cards cards) {
        System.out.println(cards.getCardstate());
        if(cards.getCardstate()==2){
            WillList will=this.willListService.queryById(cards.getWillid());
            will.setState("1");
            this.willListService.update(will);
        }
        this.cardsDao.update(cards);
        return this.queryById(cards.getCardid());
    }

    /**
     * 通过主键删除数据
     *
     * @param cardid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer cardid) {
        return this.cardsDao.deleteById(cardid) > 0;
    }

    @Override
    public Cards playCard(Cards cards) {
        Cards info = this.cardsDao.selectByWillId(cards.getWillid());
        if (info == null) {
            Integer i = this.cardsDao.insert(cards);
            return this.cardsDao.selectByWillId(cards.getWillid());
        }
        return info;
    }
}